<template>
  <el-dialog
    :title="`${isCreate ? '添加' : '编辑'}提现手续费`"
    :visible.sync="dialogVisible"
    class="dialog"
    width="360px">
    <el-form
      :model="formData"
      label-width="120px"
      ref="form"
      :rules="rules"
      size="small">
      <el-form-item label="名称" prop="name">
        <el-input v-model="formData.name"></el-input>
      </el-form-item>
      <el-form-item label="最低提现金额" prop="minVal">
        <el-input-number v-model="formData.minVal" :controls="false" :precision="2"></el-input-number>
      </el-form-item>
      <el-form-item label="最高提现金额" prop="maxVal">
        <el-input-number v-model="formData.maxVal" :controls="false" :min="formData.minVal" :precision="2"></el-input-number>
      </el-form-item>
      <el-form-item label="手续费比例" prop="chargeRatio">
        <el-input-number v-model="formData.chargeRatio" :controls="false" :max="100"></el-input-number>
      </el-form-item>
    </el-form>
    <dialog-footer
      slot="footer"
      @cancel="dialogVisible = false"
      @confirm="confirm"
    />
  </el-dialog>
</template>
<script>
import { saveWithdrawRule, updateWithdrawRule } from '@/api/base-config';

export default {
  props: {
    initFormData: Object,
    isCreate: Boolean,
  },
  data() {
    return {
      formData: {
        ...this.initFormData,
      },
      dialogVisible: false,
      rules: {
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        minVal: [{ required: true, message: '最低提现不能为空', trigger: 'blur' }],
        maxVal: [{ required: true, message: '最高提现金额不能为空', trigger: 'blur' }],
        chargeRatio: [{ required: true, message: '手续费比例不能为空', trigger: 'blur' }],
      },
    };
  },
  watch: {
    initFormData(val) {
      this.formData = { ...val };
    },
  },
  methods: {
    async confirm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            const {
              chargeRatio, maxVal, minVal, name, id,
            } = this.formData;
            if (this.isCreate) {
              await saveWithdrawRule({
                ...this.formData,
                maxVal: maxVal * 100,
                minVal: minVal * 100,
              });
            } else {
              await updateWithdrawRule({
                chargeRatio,
                maxVal: maxVal * 100,
                minVal: minVal * 100,
                name,
                id,
              });
            }
            this.dialogVisible = false;
            this.$emit('confirm');
          } catch (err) {
            console.log(err);
          }
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
  .dialog {
    ::v-deep .el-input__inner {
      width: 200px;
    }
  }
</style>
